<?php

namespace app\admin\controller;

use think\facade\View;
use think\Controller;
use think\Db;
use think\db\Where;
use app\admin\model\SysuserModel;
use think\facade\Session;
use auth\Auth;
use think\facade\Config;
use think\facade\Request;
use think\facade\App;

class PublicController extends Controller
{
    public function index()
    {
        $sessionid = session('user');
        //session(null, 'think');
        if (isset ($sessionid)) {
            $this->redirect('Index/index');
        } else {
            return View::fetch();
        }
    }

    function _initialize()
    {
        //查list;
        //import('ORG.Util.Operation');
        //$operation_obj = new \Org\Util\Operation();
        ////$log_list = $operation_obj -> logList(array('member_id' => 2086));
        ////记录日志
        ////$operation_obj -> checkTableIsExist();//创建日志记录表，如果不存在则新建
        //$operation_obj -> writeLog(APP_NAME.'_'.MODULE_NAME .'_'.ACTION_NAME,'系统后台用户登录操作');
    }

    // 用户登出
    public function logout()
    {
        $sessionid = session('sysuser');
        if (isset ($sessionid)) {
            session(null, 'think');
            //session_destroy();
            //$this->assign("jumpUrl", __URL__ . '/index/');
            $this->success('登出成功！', 1);
        } else {
            $this->success('已经登出！', 1);
        }
    }

    // 登录检测
    public function checklogin()
    {
        $account = $this->request->param("account");
        $password = md5($this->request->param("password"));
        $verify = md5($this->request->param("verify"));
        if (empty ($account)) {
            $this->error('帐号必须！');
        }
        if (empty ($password)) {
            $this->error('密码必须！');
        }
        $login = array();
        //使用用户名、密码和状态的方式进行认证
        $con['account'] = $account;
        $con['password'] = $password;
        $userlist = Db::name("sysuser")->where(new Where($con))->select();
        //dump($userlist);
        if (!$userlist) {
            $this->error('用户名或密码错误', 0);
        } else {
            $user = SysuserModel::get($userlist[0]['id']);
            //$user->last_login_time = time();
            //$user->login_count = array(
            //    'exp',
            //    'login_count+1'
            //);
            //$user->last_login_ip = get_client_ip();
            //$user->save();

            //$res = Db::name('sysuser')
            //    ->where('id', $userlist[0]['id'])
            //    ->inc('login_count')
            //    ->exp('last_login_ip', $this->request->ip())
            //    ->exp('last_login_time', time())
            //    ->update();

            //$ip = $this->request->ip();
            //$time = time();
            //$data = array();
            //$data = $userlist[0];
            //$data['id'] = $userlist[0]['id'];
            //$data['last_login_time'] = $time;
            //$data['last_login_ip'] = $ip;
            //$userlist = $user->create($data);

            if (1) {
                $usersessionlist = Db::name("sysuser")->find($userlist[0]['id']);
                session('sysuser', $usersessionlist);
                //取出相关角色信息
                $rul = Db::query("select * from sysrole sr,sysrole_user sru WHERE sr.id=sru.role_id and sru.user_id=:user_id", ['user_id' => $userlist[0]['id']]);
                session('sysuser.sysrole', $rul);
                //取出相关可访问资源信息
                $node = Db::query("select DISTINCT sysmenu.* from sysmenu inner join sysrole_menu on sysmenu.id=sysrole_menu.menu_id inner join sysrole_user on sysrole_menu.role_id=sysrole_user.role_id and sysrole_user.user_id=:user_id", ['user_id' => $userlist[0]['id']]);
                session('sysuser.sysmenu', $node);
                //重组权限节点为数组
                if (session('sysuser.account') == 'admin') {
                    $node = Db::name("sysmenu")->select();
                    session('sysuser.sysmenu', $node);
                    foreach ($node as $key => $value) {
                        $nodesname[$key] = $value['name'];
                        session('menunames', $nodesname);
                    }
                } else {
                    foreach (session('sysuser.sysmenu') as $key => $value) {
                        $nodesname[$key] = $value['name'];
                        session('menunames', $nodesname);
                    }
                }
                //dump(Session::get());
                //exit;
                //取出所在项目组的信息
                // $groups = M('groups');
                // $con2['id'] = array('in',$userlist['groupsid']);
                // $groups = $groups->where($con2)->select();

                $auth = new Auth();
                //$groups = $auth->getGroups(session('user.id'));
                //session('user.groups', $groups[0]);
                $this->success('登录成功！', 1);
            } else {
                $this->error('登录失败！请检查存入session错误！', 1);
            }

        }
    }

    public function verify()
    {
        $type = isset ($_GET['type']) ? $_GET['type'] : 'gif';
        import("@.ORG.Util.Image");
        Image:: buildImageVerify(4, 1, $type);
    }

    //添加用户提交处理
    public function reg()
    {
        $m = D("User");
        $_POST['password'] = md5(123456);
        $groupsIds = $_POST['groupsIds'];
        $groupsIdsstr = implode(",", $groupsIds);
        $_POST['groupsid'] = $groupsIdsstr;
        //dump($_POST);
        if (!$m->create($_POST)) {
            $this->error($m->getError(), 3);
        } else {
            if ($result = $m->add()) {
                $this->addRole($result, 2);
                $this->addGroup($result, $groupsIds);
                $this->success('添加用户成功！', 1);
            } else {
                $this->error('添加用户失败！' . $m->getError(), 0);
            }
        }
    }

    protected function addRole($userId, $roleId)
    {
        //注册用户自动加入相应权限组
        $RoleUser = M("role_user");
        $data['user_id'] = $userId;
        $data['role_id'] = $roleId;
        $RoleUser->create($data);
        $RoleUser->add($data);
    }

    protected function addGroup($userId, $groupsIds)
    {
        //用户加入相应项目组
        $RoleUser = M("groups_user");
        foreach ($groupsIds as $key => $v) {
            //$userlist[$key]=$v[id];
            $data['user_id'] = $userId;
            $data['groups_id'] = $v;
            $RoleUser->create($data);
            $RoleUser->add($data);
        }

    }

    public function publicprojectview()
    {
        $n = M("Groups");
        import("ORG.Util.Page"); //导入分页类
        $count = $n->count(); //计算总数
        //$p = new Page($count,$rows);order($sort+','+$order)->
        $list = $n->order('gname desc')->select();
        //$list = $n->select();
        $list = json_encode($list);
        $result = '{"total":' . $count . ',"rows":' . $list . '}';
        echo($list); //输出json数据
    }

    public function uploadfile()
    {
        $type = $_REQUEST['type'];
        $imgurl = $_REQUEST['imgurl'];
        $res = array();
        if (!empty($_FILES)) {
            import("ORG.Net.UploadFile");
            $upload = new UploadFile();
            $upload->maxSize = 2048000;
            $upload->allowExts = array('jpg', 'jpeg', 'gif', 'png');
            $upload->savePath = "./Weixin/Tpl/Res/upload/";
            $upload->saveRule = 'my_filename';
            //$upload -> saveRule = uniqid;
            $upload->thumb = true; //设置缩略图
            $upload->thumbType = 0;//0按照等比例进行缩放
            // $upload->imageClassPath = "ORG.Util.Image";
            // $upload->thumbPrefix = "130_,75_,24_"; //生成多张缩略图
            // $upload->thumbMaxWidth = "130,75,24";
            // $upload->thumbMaxHeight = "130,75,24";
            $upload->thumbMaxWidth = "500";
            $upload->thumbMaxHeight = "500";//上传规则
            $upload->thumbRemoveOrigin = true;//删除原图

            if (!$upload->upload()) {
                //$this->error($upload->getErrorMsg());//获取失败信息
                $this->error('失败！' . $upload->getErrorMsg(), 0);
                $res['error'] = 0;
                $res['msg'] = $upload->getErrorMsg();
                $res['imgurl'] = '失败！';
            } else {
                if (!empty($imgurl)) {
                    $flag = unlink("./Weixin/Tpl/Res/upload/" . $imgurl);
                }
                $info = $upload->getUploadFileInfo();
                //获取成功信息
                $res['error'] = 1;
                $res['msg'] = "成功！---" . $flag;
                $res['imgurl'] = "thumb_" . $info[0]['savename'];
            }
        } else {
            $res['error'] = 0;
            $res['msg'] = "请选择上传文件！";
            $res['imgurl'] = null;
        }
        echo json_encode($res);
    }

    public function map()
    {
        return View::fetch();
    }

    public function welcome0()
    {
        return View::fetch();
    }

    public function welcome1()
    {
        return View::fetch();
    }

    public function welcome2()
    {
        return View::fetch();
    }

    public function welcome3()
    {
        return View::fetch();
    }

    public function message()
    {
        return View::fetch();
    }

    public function userInfo()
    {
        $isPost = $this->request->isPost();
        if ($isPost) {
            $userid = input('id');
            $password = input('password');
            $password = md5($password);
            $sysuser = new SysuserModel();
            $res = SysuserModel::update(['password' => $password], ['id' => $userid]);
            if ($res) {
                $this->success("成功");
            } else {
                $this->error("失败" . $sysuser->getError());
            }

        } else {
            return View::fetch();
        }
    }

    public function configlist()
    {
        dump(Config::get());
    }

    // 后台首页 查看系统信息
    public function main()
    {
        $info = array(
            '操作系统'                 => PHP_OS,
            '运行环境'                 => $_SERVER["SERVER_SOFTWARE"],
            'PHP运行方式'              => php_sapi_name(),
            'PHP版本'                => phpversion(),
            'mysql_version'        => $this->_mysql_version(),
            'mysql_size'           => $this->_mysql_db_size(),
            'ThinkPHP版本'           => App::version() . ' [ <a href="http://thinkphp.cn" target="_blank">查看最新版本</a> ]',
            '上传附件限制'               => ini_get('upload_max_filesize'),
            '执行时间限制'               => ini_get('max_execution_time') . '秒',
            '服务器时间'                => date("Y年n月j日 H:i:s"),
            '北京时间'                 => gmdate("Y年n月j日 H:i:s", time() + 8 * 3600),
            '服务器域名/IP'             => $_SERVER['SERVER_NAME'] . ' [ ' . gethostbyname($_SERVER['SERVER_NAME']) . ' ]',
            '剩余空间'                 => round((@disk_free_space(".") / (1024 * 1024)), 2) . 'M',
            'register_globals'     => get_cfg_var("register_globals") == "1" ? "ON" : "OFF",
            'magic_quotes_gpc'     => (1 === get_magic_quotes_gpc()) ? 'YES' : 'NO',
            'magic_quotes_runtime' => (1 === get_magic_quotes_runtime()) ? 'YES' : 'NO',
            '系统设置'                 => ' <a href="/admin/public/configlist" target="_blank">查看系统设置</a> ',
        );
        $this->assign('info1', $info);
        // dump($info);
        return View::fetch();
    }

    private function _mysql_version()
    {
        $version = Db::query("select version() as ver");
        return $version[0]['ver'];
    }

    private function _mysql_db_size()
    {
        $sql = "SHOW TABLE STATUS FROM " . Config::get('database.database');
        $tblPrefix = Config::get('database.prefix');
        if ($tblPrefix != null) {
            $sql .= " LIKE '{$tblPrefix}%'";
        }
        $row = Db::query($sql);
        $size = 0;
        foreach ($row as $value) {
            $size += $value["data_length"] + $value["index_length"];
        }
        return round(($size / 1048576), 2) . 'M';
    }
}